package com.example.criminalintent

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.example.criminalintent.model.Crime
import com.example.criminalintent.model.CrimeLab
import com.example.criminalintent.view.CrimeFragment
import java.util.*

class CrimePagerActivity : AppCompatActivity(),CrimeFragment.Callbacks {
    override fun onCrimeUpdate(crime: Crime) {
    }

    private var mViewPager: ViewPager? = null
    private var mCrimes: List<Crime>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_crime_pager)
        val crimeId = intent.getSerializableExtra(EXTRA_CRIME_ID) as UUID

        mViewPager = findViewById<ViewPager>(R.id.crime_view_pager)
        mCrimes = CrimeLab[this].getCrimes()
        val fragmentManager = supportFragmentManager

        mViewPager!!.adapter = object : FragmentStatePagerAdapter(fragmentManager, 0) {
            override fun getItem(position: Int): Fragment {
                val cur = mCrimes!![position]
                return CrimeFragment.newInstance(cur.mId!!)
            }

            override fun getCount(): Int {
                return mCrimes!!.size
            }
        }

        for (i in 0 until mCrimes!!.size) {
            if (mCrimes!![i].mId == crimeId) {
                mViewPager!!.currentItem = i
                break
            }
        }
    }

    companion object {

        private const val EXTRA_CRIME_ID = "com.example.criminalintent.crime_id"

        fun newIntent(packageContext: Context, crimeId: UUID): Intent {
            val intent = Intent(packageContext, CrimePagerActivity::class.java)
            intent.putExtra(EXTRA_CRIME_ID, crimeId)
            return intent
        }
    }
}
